package com.traveldream.beans.converters;

import javax.ejb.EJB;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import com.traveldream.entities.Excursion;
import com.traveldream.entities.Flight;
import com.traveldream.entity_managers.ProductManager;

@FacesConverter(value = "flightConverter")
public class FlightConverter implements Converter{

	@EJB
	private ProductManager pm; // instance of product manager
	
	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		
		if (value.isEmpty())
            return null;
        try {
            int id = Integer.parseInt(value);
            Flight flight = pm.findFlight(id);
            System.out.print("Converted {0} to {1}"+new Object[] {value, flight});
            return flight;
        } catch (NumberFormatException e) {
            return new Flight();
        }
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if (value == null || value.toString().isEmpty() || !(value instanceof Flight))
            return "";
        return String.valueOf(((Flight) value).getProductId());
	}

}
